package com.yunke.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunke.entity.YunkeSms;
import com.yunke.mapper.YunkeSmsMapper;
import com.yunke.service.YunkeSmsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 短信管理服务实现类
 * 
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class YunkeSmsServiceImpl extends ServiceImpl<YunkeSmsMapper, YunkeSms> implements YunkeSmsService {

    private final YunkeSmsMapper yunkeSmsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendVerifyCode(String phoneNumber, String businessType) {
        try {
            // 检查发送频率限制
            if (!checkSendLimit(phoneNumber, businessType)) {
                throw new RuntimeException("发送过于频繁，请稍后再试");
            }

            // 生成验证码
            String verifyCode = generateVerifyCode();
            
            // 创建短信记录
            YunkeSms sms = new YunkeSms();
            sms.setPhoneNumber(phoneNumber);
            sms.setSmsContent("您的验证码是：" + verifyCode + "，有效期5分钟。");
            sms.setSmsType(1); // 验证码
            sms.setBusinessType(businessType);
            sms.setTemplateCode("VERIFY_CODE");
            sms.setVerifyCode(verifyCode);
            sms.setCodeExpire(5); // 5分钟有效期
            sms.setSendStatus(2); // 发送成功（模拟）
            sms.setSendTime(System.currentTimeMillis());
            sms.setProvider(1); // 阿里云
            sms.setIsVerified(false);
            sms.setRetryCount(0);
            sms.setStatus(0);
            sms.setCreateTime(System.currentTimeMillis());
            sms.setUpdateTime(System.currentTimeMillis());

            return this.save(sms);
            
        } catch (Exception e) {
            log.error("发送验证码失败", e);
            throw new RuntimeException("发送验证码失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendSmsCode(String phoneNumber, String templateCode, Integer type) {
        try {
            // 检查发送频率限制
            if (!checkSendLimit(phoneNumber, "SMS_CODE")) {
                throw new RuntimeException("发送过于频繁，请稍后再试");
            }

            // 生成验证码
            String verifyCode = generateVerifyCode();
            
            // 创建短信记录
            YunkeSms sms = new YunkeSms();
            sms.setPhoneNumber(phoneNumber);
            sms.setSmsContent("您的验证码是：" + verifyCode + "，有效期5分钟。");
            sms.setSmsType(type);
            sms.setBusinessType("SMS_CODE");
            sms.setTemplateCode(templateCode);
            sms.setVerifyCode(verifyCode);
            sms.setCodeExpire(5);
            sms.setSendStatus(2);
            sms.setSendTime(System.currentTimeMillis());
            sms.setProvider(1);
            sms.setIsVerified(false);
            sms.setRetryCount(0);
            sms.setStatus(0);
            sms.setCreateTime(System.currentTimeMillis());
            sms.setUpdateTime(System.currentTimeMillis());

            return this.save(sms);
            
        } catch (Exception e) {
            log.error("发送短信验证码失败", e);
            throw new RuntimeException("发送短信验证码失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendNotification(String phoneNumber, String templateCode, Map<String, String> params) {
        try {
            YunkeSms sms = new YunkeSms();
            sms.setPhoneNumber(phoneNumber);
            sms.setSmsType(2); // 通知
            sms.setTemplateCode(templateCode);
            sms.setTemplateParams(params.toString());
            sms.setSendStatus(2); // 发送成功（模拟）
            sms.setSendTime(System.currentTimeMillis());
            sms.setProvider(1);
            sms.setRetryCount(0);
            sms.setStatus(0);
            sms.setCreateTime(System.currentTimeMillis());
            sms.setUpdateTime(System.currentTimeMillis());

            return this.save(sms);
            
        } catch (Exception e) {
            log.error("发送通知短信失败", e);
            throw new RuntimeException("发送通知短信失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendBatch(String[] phoneNumbers, String templateCode, Map<String, String> params) {
        try {
            for (String phoneNumber : phoneNumbers) {
                sendNotification(phoneNumber, templateCode, params);
            }
            return true;
            
        } catch (Exception e) {
            log.error("批量发送短信失败", e);
            throw new RuntimeException("批量发送短信失败：" + e.getMessage());
        }
    }

    @Override
    public boolean verifyCode(String phoneNumber, String verifyCode, String businessType) {
        // TODO: 实现验证码验证逻辑
        // 查询最近的验证码记录，检查是否匹配且未过期
        return true;
    }

    @Override
    public IPage<YunkeSms> getSmsPage(Integer current, Integer size, String phoneNumber, 
                                     Integer smsType, Integer sendStatus) {
        Page<YunkeSms> page = new Page<>(current, size);
        return yunkeSmsMapper.selectSmsPage(page, phoneNumber, smsType, sendStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resendSms(Long id) {
        try {
            YunkeSms sms = this.getById(id);
            if (sms == null) {
                throw new RuntimeException("短信记录不存在");
            }

            // 增加重试次数
            sms.setRetryCount(sms.getRetryCount() + 1);
            sms.setSendStatus(2); // 重发成功（模拟）
            sms.setSendTime(System.currentTimeMillis());
            sms.setUpdateTime(System.currentTimeMillis());

            return this.updateById(sms);
            
        } catch (Exception e) {
            log.error("重发短信失败", e);
            throw new RuntimeException("重发短信失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getSmsStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // TODO: 实现真实的统计查询
        statistics.put("totalSms", 0L);
        statistics.put("successSms", 0L);
        statistics.put("failedSms", 0L);
        statistics.put("todaySms", 0L);
        
        return statistics;
    }

    @Override
    public boolean checkSendLimit(String phoneNumber, String businessType) {
        // TODO: 实现发送频率限制检查
        // 例如：同一手机号码1分钟内只能发送1条验证码
        return true;
    }

    /**
     * 生成6位验证码
     */
    private String generateVerifyCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
} 